var roleManage = function() {

	var _init = function() {

		var  table = $('#table_role');
		 var form = $('#modal_new_role').serializeObject();
		table.dataTable({
					"processing" : true,
					// 开启服务器模式
					serverSide : true,
					"ajax" : {
						url : "/a/wxconf/groups"// 列表查询
					},
					"autoWidth" : false,
					"columns" : [
							{
								"width" : "10%",
								"data" : "proName",
							},
							{
								"width" : "5%",
								"data" : "proPrice",
								"render" : function(data, type, row, meta) {
									return row.proPrice/100;
									}
							},
							{
								"width" : "10%",
								"data" : "proGroupPrice",
								"render" : function(data, type, row, meta) {
									return row.proGroupPrice/100;
									}
							},
							{
								"width" : "5%",
								"data" : "groupSuccCount",
								/*"render" : function(data, type, row, meta) {
									return "--";
									}*/
							},
							{
								"width" : "10%",
								 "data": "groupDateStr",
							},
							{
								"width" : "5%",
								 "data": "groupCount",/*,
								 "render" : function(data, type, row, meta) {
										return "--";
										}*/
							},
							{
								"width" : "15%",
								 "data": "updateDate", 
								 "render" : function(data, type, row, meta) {
									 if(row.updateDate!=null){
										 return moment(data).format('YYYY-MM-DD HH:mm');
									 }else{
										 return "--";
									 }
										
									}
							},
							{
								"width" : "5%",
								 "data": "status",
								 "render" : function(data, type, row, meta) {
								     if(row.status=="0"){
								    	 return "未开启";
								     }else if(row.status=="1"){
								    	 return "进行中";
									} else if(row.status=="2"){
								    	 return "拼团成功";
									}else if(row.status=="3"){
								    	 return "拼团失败";
									}else if(row.status=="4"){
									    	 return "成功结束";
										}
								}
							},
							{
								"width" : "20%",
								 "render" : function(data, type, row, meta) {
									     if(row.status=="0"){
									    	return  "<button type=\"button\" class=\"btn green btn_open_pintuan\" >上架</button><button type=\"button\" class=\"btn blue btn_edit_pintuan\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button>";
									     }
									     else if(row.status=="1"){
												return "<button type=\"button\" class=\"btn blue btn_close_pintuan\">下架</button>";
											}else if(row.status=="2"){
												return "";
											}else{
												return	"<button type=\"button\" class=\"btn red btn_del_role\">删除</button>";
											}
									}        
							} ],
					"language" : {
						"lengthMenu" : "每页显示 _MENU_ 条记录",
						"emptyTable" : "暂无数据记录",
						"info" : "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
						"zeroRecords" : "没有搜索到匹配记录",
						"infoEmpty" : "",
						"infoFiltered" : "",
						"processing" : ""
					},
					"destroy" : true,
					"ordering": false, 
					"pageLength" : 5,
					"order" : [ [ 5, "desc" ] ],
					"columnDefs" : [ {
						"orderable" : false,
						"targets" : [ 0, 8]
					} ],
					"dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
							+ "<t>" + "<'row'<'col-md-5'i><'col-md-7'>p>",
					"fnInitComplete" : function() {
					}
				});
		if($("input[name='id']").val()==""){
		//加载隐藏商品名称和规格
		$("#pname select").attr("disabled",true);
		$("#pspecification select").attr("disabled",true);
		}
		$("#ptype select").change(function(){
			$("#pname select").removeAttr("disabled");
			$("#pspecification select").attr("disabled",true);
			if($(this).val()!=""){
				//清空商品内容
				$('select[name="proName"]').html("<option  value=''>商品名称</option>");
				$('select[name="proSpecification"]').html("<option  value=''>商品规格</option>");
				$("input[name='proPrice']").val("0");
				var url = "/a/wxconf/group/selectProName";
				getSpellGroupProduct("ptype",$(this).val(),url);
			}
		})
		$("#pname select").change(function(){
			$("#pspecification select").removeAttr("disabled");
			if($(this).val()!=""){
				$('select[name="proSpecification"]').html("<option  value=''>商品规格</option>");
				$("input[name='proPrice']").val("0");
				var url = "/a/wxconf/group/selectProSpecification";
				getSpellGroupProduct("pname",$(this).val(),url);
			}
		})
		//根据规格显示原价
		$("#pspecification select").change(function(){
		if($(this).val()==""){
			$("input[name='proPrice']").val("0");
		}
		if($(this).val()!=""){
			var url = "/a/wxconf/group/selectProSpecificationPrice";
			getSpellGroupProduct("pspec",$(this).val(),url);
		};
			
		})
		// 删除
		table.on('click', '.btn_del_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要删除?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							// alert('提交删除');
							var _data = JSON.stringify({
								id : _id
							});
							request_role_del(_data, function(res) {
								// 正确
								table.DataTable().ajax.reload();
							}, function(err) {
								// 错误
								alert(err);
							})
						}
					}
				}
			});
		});
		
		
		//启用拼团
		table.on('click', '.btn_open_pintuan', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要上架?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							var _data = JSON.stringify({
								id : _id
							});
							//启用
							$.ajax({
								url : '/a/wxconf/groups',
								type : 'post',
								dataType : 'json',
								contentType : "application/json; charset=utf-8",
								data : _data,
							}).done(function(data) {
								if (data.status === '1') {
									table.DataTable().ajax.reload();
								} else if (data.status === '2') {
									alert(data.message);
								}
							});
						}
					}
				}
			});
		});
		
		//下架拼团
		table.on('click', '.btn_close_pintuan', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要下架?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							var _data = JSON.stringify({
								id : _id
							});
							$.ajax({
								url : '/a/wxconf/groups',
								type : 'post',
								dataType : 'json',
								contentType : "application/json; charset=utf-8",
								data : _data,
							}).done(function(data) {
								if (data.status === '1') {
									table.DataTable().ajax.reload();
								} else if (data.status === '2') {
								}
							});
						}
					}
				}
			});
		});

		table.on('click', '.btn_edit_pintuan', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
			.data(); // 操作行对象
	        var _id = oData_arr[0].id;
			window.location.href = "/p/wxconf/group/groupDetail?id="
					+ encodeURIComponent(_id);
		});
		
	$("#add_spellGroup").on("click",function(){
		window.location.href = "/p/wxconf/group/spellGroup";
		});
	
	$("#save").click(function() {

		var _data = $("#modal_new_role").serializeObject();
		if (!mdTool.validate(_data.proClass, 'require')) {
			$('#modal_new_role  .help-block').html("请选择商品分类");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		if (!mdTool.validate(_data.proName, 'require')) {
			$('#modal_new_role  .help-block').html("请选择商品名称");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		/*if (!mdTool.validate(_data.proSpecification, 'require')) {
			$('#modal_new_role  .help-block').html("请选择商品规格");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}*/
		if($("input[name='proPrice']").val()=="0"){
			$('#modal_new_role  .help-block').html("请选择商品规格");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		};
		if (!mdTool.validate(_data.proGroupPrice, 'require')) {
			$('#modal_new_role  .help-block').html("请输入拼团价");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		if (!mdTool.validate(_data.proGroupPrice,'znum')) {
			$('#modal_new_role  .help-block').html('请输入正数拼团价');
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		//保留2位小数
		if(!/^-?\d+\.?\d{0,2}$/.test(_data.proGroupPrice)){
			$('#modal_new_role  .help-block').html('拼团价小数位最多输入2位');
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		};
		
		//比较拼团价和原价
		var pgp = $("input[name='proGroupPrice']").val();
		var pg = $("input[name='proPrice']").val();
		if(parseFloat(pgp) > parseFloat(pg)){
			$('#modal_new_role  .help-block').html('拼团价不能大于商品原价');
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		
		
		if (!mdTool.validate(_data.groupSuccCount, 'require')) {
			$('#modal_new_role  .help-block').html("请输入拼团成功人数");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		if (!mdTool.validate(_data.groupSuccCount,'num')) {
			$('#modal_new_role  .help-block').html('请输入正整数拼团成功人数');
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		if (!mdTool.validate(_data.groupDateStr, 'require')) {
			$('#modal_new_role  .help-block').html("请输入拼团时长");
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		if (!mdTool.validate(_data.groupDateStr,'num')) {
			$('#modal_new_role  .help-block').html('请输入正整数拼团时长');
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		if (!mdTool.validate(_data.confineCount, 'require')) {
			$('#modal_new_role  .help-block').html("请输入每人限购数量");
			$('#modal_new_role  .help-block').css('color', 'red');
			return; 
		}
		if (!mdTool.validate(_data.confineCount,'num')) {
			$('#modal_new_role  .help-block').html('请输入正整数每人限购数量');
			$('#modal_new_role  .help-block').css('color', 'red');
			return;
		}
		_data.proClass = $("select[name='proClass'] option:selected").text();
		_data.proName = $("select[name='proName'] option:selected").text();
		_data.productId = $("select[name='proName'] option:selected").val();
		_data.productSpecId = $("select[name='proSpecification'] option:selected").val();
		//alert("_data.productId:"+_data.productId+"== _data.productSpecId="+_data.productSpecId);
		_data.proSpecification = $("select[name='proSpecification'] option:selected").text();
		var _type = _data.id == null || _data.id == '' ? "put": "post";
		$.ajax({
			url : '/a/wxconf/group',
			type : _type,
			dataType : 'json',
			contentType : "application/json; charset=utf-8",
			data : JSON.stringify(_data),
		}).done(function(data) {
			if (data.status === '1') {
				console.log('保存成功！');
				/*$('#modal_new_role .help-block').html("保存成功！");
				$("#modal_new_role .help-block").attr("style", "color:green;");*/
				//到列表页面
				window.location.href="/p/wxconf/group";
			} else if (data.status === '2') {
				// 错误
				$('#modal_new_role .help-block').html(data.message); // 返回错误信息
				$("#modal_new_role .help-block").attr("style", "color:red;");
			}
		});
	})

		 $('select[name="status"]').change(function(event){
			 var form = $('#form1').serializeObject();
			 var param =  {
					"status" : form.status
				}
			 $('#table_role').DataTable().search(JSON.stringify(param)  ).draw();
//		          table.DataTable().ajax.reload();
		      });

	}

	return {
		init : function() {
			_init();
		}

	};

}();

var roleForm = function() {
	// 新建表单验证
	return {
		init : function() {
		}

	};
}();

$(function() {
	roleManage.init();
	roleForm.init();
});

function beback(){
	window.location.href="/p/wxconf/group";
}

//获取拼团商品
function getSpellGroupProduct(flag,_data,url){
	$.ajax({
		url : url,
		type : 'post',
		dataType : 'json',
		contentType : "application/json; charset=utf-8",
		data : JSON.stringify({id:_data}),
	}).done(function(data) {
		if (data.status === '1') {
			if(flag =="ptype"){
				var datas =  data.data;
				var pname = "";
				if(datas!=null && datas.length>0 ){
					for(var i=0;i<datas.length;i++){
						 pname += '<option  value='+datas[i].id+'>'+datas[i].title+'</option>';
					}
				}else{
				}
				$('select[name="proName"]').append(pname);
			}
			if(flag =="pname"){
				var datas =  data.data;
				var proSpecification = "";
				if(datas!=null && datas.length>0){
					for(var i=0;i<datas.length;i++){
						proSpecification += '<option  value='+datas[i].id+'>'+datas[i].name+'</option>';
					}
					$("select[name='proSpecification']").append(proSpecification);
				}else{
					$("#pspecification select").attr("disabled",true);
					//查找该商品的原价
					$.ajax({
						url : '/a/wxconf/group/selectProduct',
						type : 'post',
						dataType : 'json',
						contentType : "application/json; charset=utf-8",
						data : JSON.stringify({id:_data}),
					}).done(function(data) {
						if (data.status === '1') {
							$("input[name='proPrice']").val(data.data.price/100);
						}else{
							
						}
						
					})
				}
			}
			if(flag =="pspec"){
				var datas =  data.data;
				var proPrice = "";
				if(datas!=null){
					$("input[name='proPrice']").val(datas.price/100);
				}
			}
		} else if (data.status === '2') {
			
		}
	});
	
}



